<template>
  <div>
    <div style="margin-top: 5px; margin-bottom: 5px">
      <el-input
        v-model="name"
        placeholder="请输入物品名"
        style="width: 200px"
        @keyup.enter="loadPost"
        ><template><el-icon class="el-input__icon"></el-icon></template
      ></el-input>
      <el-select v-model="storage" placeholder="请选择仓库" style="width: 200px; margin: 0 10px">
        <el-option v-for="item in storageData" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="goodstype" placeholder="请选择分类" style="width: 200px">
        <el-option v-for="item in goodstypeData" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <el-button type="primary" style="margin-left: 10px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" @click="add" style="margin-left: 10px">新增</el-button>
      <el-button type="primary" @click="inGoods" style="margin-left: 10px" v-if="user.roleId != 2"
        >入库</el-button
      >
      <el-button type="primary" @click="outGoods" style="margin-left: 10px" v-if="user.roleId != 2"
        >出库</el-button
      >
    </div>
    <el-table
      :data="tableData"
      style="height: 100; text-align: center"
      :header-cell-style="{ background: '#f2f5fc', color: '#555', textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      border
      stripe
      highlight-current-row
      @current-change="selectCurrentChange"
    >
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="物品名" width="100" />
      <el-table-column prop="storage" label="仓库" :formatter="formatStorage" />
      <el-table-column prop="goodstype" label="分类" :formatter="formatType" />
      <el-table-column prop="count" label="数量" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column prop="operate" label="操作" v-if="user.roleId != 2">
        <template v-slot="scope">
          <el-button type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            title="确定要删除吗？"
            @confirm="del(scope.row.id)"
          >
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="text-align: center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-dialog
        v-model="dialogVisible"
        title="添加物品信息"
        width="30%"
        :before-close="handleClose"
        center
      >
        <el-form
          ref="form"
          :rules="rules"
          :model="form"
          label-width="80px"
          style="text-align: center; max-width: 500px"
        >
          <el-form-item label="物品名" prop="name">
            <el-col :span="20">
              <el-input v-model="form.name" />
            </el-col>
          </el-form-item>
          <el-form-item label="仓库" prop="storage">
            <el-col :span="20">
              <el-select v-model="form.storage" placeholder="请选择仓库">
                <el-option
                  v-for="item in storageData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="分类" prop="goodstype">
            <el-col :span="20">
              <el-select v-model="form.goodstype" placeholder="请选择分类">
                <el-option
                  v-for="item in goodstypeData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="数量" prop="count">
            <el-col :span="20">
              <el-input v-model="form.count" />
            </el-col>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-col :span="20">
              <el-input type="textarea" v-model="form.remark" />
            </el-col>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save"> 保存 </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog
        v-model="inDialogVisible"
        :title="title"
        width="30%"
        :before-close="handleClose"
        center
      >
        <el-dialog
          v-model="innerVisible"
          width="50%"
          title="用户选择"
          :before-close="handleClose"
          style="text-align: center"
          append-to-body
        >
          <SelectUser @doSelectUser="doSelectUser" style="text-align: center"></SelectUser>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="closeSelect">取消</el-button>
              <el-button type="primary" @click="confirmUser"> 确定 </el-button>
            </div>
          </template>
        </el-dialog>
        <el-form
          ref="form1"
          :rules="rule1"
          :model="form1"
          label-width="80px"
          style="text-align: center; max-width: 500px"
        >
          <el-form-item label="物品名" prop="name">
            <el-col :span="20">
              <el-input v-model="form1.name" readonly />
            </el-col>
          </el-form-item>
          <el-form-item label="申请人" prop="username">
            <el-col :span="20">
              <el-input v-model="form1.username" @click="selectUser" />
            </el-col>
          </el-form-item>
          <el-form-item label="数量" prop="count">
            <el-col :span="20">
              <el-input v-model="form1.count" />
            </el-col>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-col :span="20">
              <el-input type="textarea" v-model="form1.remark" />
            </el-col>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="inDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm('form1')"> 保存 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ElMessageBox } from 'element-plus';
import { reactive } from 'vue';
import SelectUser from '../user/SelectUser';
export default {
  name: 'GoodsManage',
  components: { SelectUser },
  data() {
    let checkCount = (rule, value, callback) => {
      if (value > 9999) {
        callback(new Error('数量输入过大'));
      } else {
        callback();
      }
    };
    return {
      user: JSON.parse(sessionStorage.getItem('User')),
      storageData: [],
      goodstypeData: [],
      tableData: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      name: '',
      storage: '',
      goodstype: '',
      dialogVisible: false,
      inDialogVisible: false,
      innerVisible: false,
      tempUser: '',
      title: '入库',
      currentRow: {},
      form: {
        id: '',
        name: '',
        storage: '',
        goodstype: '',
        count: '',
        remark: '',
      },
      form1: {
        goods: '',
        name: '',
        count: '',
        username: '',
        userid: '',
        adminId: '',
        remark: '',
        action: '1',
      },
      rules: {
        name: [
          { required: true, message: '请输入物品名', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在1到8个字符', trigger: 'blur' },
        ],
        storage: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
        goodstype: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        count: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数字', trigger: 'blur' },
          { validator: checkCount, trigger: 'blur' },
        ],
      },
      rule1: {
        username: [
          { required: true, message: '请输入申请人名字', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在1到8个字符', trigger: 'blur' },
        ],
        count: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数字', trigger: 'blur' },
          { validator: checkCount, trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    loadPost() {
      this.$axios
        .post(this.$httpUrl + '/goods/listPage', {
          pageSize: this.pageSize,
          pageNum: this.pageNum,
          param: {
            name: this.name,
            goodstype: this.goodstype + '',
            storage: this.storage + '',
          },
        })
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data;
            this.total = res.total;
          } else {
            alert('获取数据失败');
          }
        });
    },
    loadStorage() {
      this.$axios
        .get(this.$httpUrl + '/storage/list')
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.storageData = res.data;
          } else {
            alert('获取数据失败');
          }
        });
    },
    loadGoodstype() {
      this.$axios
        .get(this.$httpUrl + '/goodstype/list')
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.goodstypeData = res.data;
          } else {
            alert('获取数据失败');
          }
        });
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.loadPost();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadPost();
    },
    resetParam() {
      this.name = '';
      this.storage = '';
      this.goodstype = '';
      this.loadPost();
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    resetIntForm() {
      this.$refs.form1.resetFields();
    },
    add() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.resetForm();
      });
    },
    inGoods() {
      this.title = '入库';
      try {
        if (
          this.currentRow.id == null ||
          this.currentRow.id == undefined ||
          typeof this.currentRow == 'undefined'
        ) {
          alert('请选择记录');
          return;
        }
        this.inDialogVisible = true;
        this.$nextTick(() => {
          this.resetIntForm();
        });
        this.$nextTick(() => {
          this.form1.action = '1';
          this.form1.name = this.currentRow.name;
          (this.form1.goods = this.currentRow.id), (this.form1.adminId = this.user.id);
        });
      } catch (error) {
        this.$message.error('操作失败！' + error);
      }
    },
    outGoods() {
      this.title = '出库';
      try {
        if (
          this.currentRow.id == null ||
          this.currentRow.id == undefined ||
          typeof this.currentRow == 'undefined'
        ) {
          alert('请选择记录');
          return;
        }
        this.inDialogVisible = true;
        this.$nextTick(() => {
          this.resetIntForm();
        });
        this.$nextTick(() => {
          this.form1.action = '2';
          this.form1.name = this.currentRow.name;
          (this.form1.goods = this.currentRow.id), (this.form1.adminId = this.user.id);
        });
      } catch (error) {
        this.$message.error('操作失败！' + error);
      }
    },
    doSelectUser(val) {
      this.tempUser = val;
    },
    confirmUser() {
      this.form1.username = this.tempUser.name;
      this.form1.userid = this.tempUser.id;
      this.innerVisible = false;
    },
    closeSelect() {
      this.innerVisible = false;
      this.resetIntForm();
      this.tempUser = '';
    },
    del(id) {
      this.$axios
        .get(this.$httpUrl + '/goods/del?id=' + id)
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '删除成功！',
              type: 'success',
            });
          } else {
            this.$message.error('删除失败！');
          }
          this.loadPost();
        });
    },
    mod(row) {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.form.id = row.id;
        this.form.name = row.name;
        this.form.storage = row.storage;
        this.form.goodstype = row.goodstype;
        this.form.count = row.count;
        this.form.remark = row.remark;
      });
    },
    doSave() {
      this.$axios
        .post(this.$httpUrl + '/goods/save', this.form)
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '添加数据成功！',
              type: 'success',
            });
            this.dialogVisible = false;
            this.loadPost();
            this.resetForm();
          } else {
            this.$message.error('添加数据失败！');
          }
        });
    },
    submitForm(form1) {
      this.$refs[form1].validate((valid) => {
        //开启校验
        if (valid) {
          // 如果校验通过，请求接口，允许提交表单
          this.$axios
            .post(this.$httpUrl + '/record/save', this.form1)
            .then((res) => res.data)
            .then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: '添加数据成功！',
                  type: 'success',
                });
                this.inDialogVisible = false;
                this.loadPost();
              } else {
                this.$message.error('添加数据失败！');
              }
            });
        } else {
          //校验不通过
          this.$message.error('添加数据失败！');
          return false;
        }
      });
    },
    selectUser() {
      this.innerVisible = true;
    },
    doMod() {
      this.$axios
        .post(this.$httpUrl + '/goods/update', this.form)
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '修改数据成功！',
              type: 'success',
            });
            this.form = {};
            this.dialogVisible = false;
            this.loadPost();
          } else {
            this.$message.error('修改数据失败！');
          }
        });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (valid) {
            if (this.form.id) {
              this.doMod();
            } else {
              this.doSave();
            }
          }
        } else {
          this.$message({
            message: '操作失败!',
            type: 'error',
          });
        }
      });
    },
    handleClose() {
      ElMessageBox.confirm('你确定要关闭吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.dialogVisible = false;
          this.inDialogVisible = false;
          this.innerVisible = false;
        })
        .catch(() => {});
    },
    selectCurrentChange(val) {
      this.currentRow = val;
    },
    formatStorage(row) {
      let temp = this.storageData.find((item) => {
        return item.id == row.storage;
      });
      return temp && temp.name;
    },
    formatType(row) {
      let temp = this.goodstypeData.find((item) => {
        return item.id == row.goodstype;
      });
      return temp && temp.name;
    },
  },
  created() {
    // this.loadGet();
    this.loadStorage();
    this.loadGoodstype();
    this.loadPost();
  },
};
</script>

<style scoped></style>
